package cn.wolfcode.education.service.impl;

import cn.wolfcode.education.domain.Attentance;
import cn.wolfcode.education.domain.Classgrade;
import cn.wolfcode.education.domain.Employee;
import cn.wolfcode.education.mapper.AttentanceMapper;
import cn.wolfcode.education.query.AttentanceQuery;
import cn.wolfcode.education.service.IAttentanceService;
import cn.wolfcode.education.util.PageResult;
import cn.wolfcode.education.util.TimeUtil;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

@Service
public class AttentanceServiceImpl implements IAttentanceService {

    @Autowired
    private AttentanceMapper attentanceMapper;

    public PageResult query(AttentanceQuery qo) {
        int total = attentanceMapper.queryForCount(qo);
        if (total == 0) {
            return new PageResult();
        }
        List<Attentance> rows = attentanceMapper.queryForList(qo);
        return new PageResult(total, rows);
    }

    //签到保存操作
    public void saveForSignOn(Employee employee) throws Exception {
        //判断当前用户是否已经签到
        Attentance nowAttentance = attentanceMapper.selectSignOnByEmployeeId(employee.getId());
        if (nowAttentance != null) {
            throw new Exception("今天已经签到!");
        }
        Attentance attentance = new Attentance();
        String realName = employee.getRealName();
        Date date = new Date();
        attentance.setSignOn(date);
        String time = "08:30:00";
        if (TimeUtil.compare(time)) {
            attentance.setOnStatus(true);
        } else {
            attentance.setOnStatus(false);
        }
        attentance.setEmployee(employee);
        attentance.setNowDate(new Date());
        attentanceMapper.saveForSignOn(attentance);
    }

    //签退操作
    public void saveForSignOut(Employee employee) throws Exception {
        //判断当前用户是否已经签过到
        Attentance nowAttentance = attentanceMapper.selectSignOnByEmployeeId(employee.getId());
        if (nowAttentance != null) {
            //判断是否已经签退
            if (nowAttentance.getSignOut() != null) {
                throw new Exception("今天已签退,无需再签");
            }
            nowAttentance.setSignOut(new Date());
            String time = "17:00:00";
            if (TimeUtil.compare(time)) {
                nowAttentance.setDownStatus(true);
            } else {
                nowAttentance.setDownStatus(false);
            }
            nowAttentance.setEmployee(employee);
            attentanceMapper.saveForSignOut(nowAttentance);
        }
    }

    public void saveForSignUp(Employee employee) throws Exception {
        //判断当前用户是否已经签过到
        Attentance nowAttentance = attentanceMapper.selectSignOnByEmployeeId(employee.getId());
        if(nowAttentance != null){
            throw new Exception("已经签到,无需补签");
        }
    }
}
